package com.tanhua.dubbo.api;


import com.tanhua.model.mongo.Friend;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class FriendApiImpl implements FriendApi {
    @Autowired
    private MongoTemplate mongoTemplate;


    @Override
    public void addFriend(Long userId, Long friendId) {
        //首先查看friend表中是否已经存在好友关系
        Query query1 = Query.query(Criteria.where("userId").is(userId).and("friendId").is(friendId));
        if (!mongoTemplate.exists(query1, Friend.class)) {
            //不存在，添加本账户对好友账户的ID
            Friend friend1 = new Friend();
            friend1.setUserId(userId);
            friend1.setFriendId(friendId);
            friend1.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend1);
        }

        //判断好友是否和本账户已经存在好友关系
        Query query2 = Query.query(Criteria.where("userId").is(friendId).and("friendId").is(userId));
        if (!mongoTemplate.exists(query2, Friend.class)) {
            //不存在，添加好友账号到本账户的ID
            Friend friend2 = new Friend();
            friend2.setUserId(friendId);
            friend2.setFriendId(userId);
            friend2.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend2);
        }

    }

    @Override
    public List<Friend> findByUserId(Long userId, Integer page, Integer pagesize) {
        Query query = Query.query(Criteria.where("userId").is(userId))
                .skip((page - 1) * pagesize).limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        return mongoTemplate.find(query, Friend.class);
    }

    @Override
    public boolean queryFriend(Long userId, Long friendId) {
        Query query1 = Query.query(Criteria.where("userId").is(userId).and("friendId").is(friendId));
        boolean exists = mongoTemplate.exists(query1, Friend.class);
        return exists;
    }

    @Override
    public void removeFriend(Long userId, Long friendId) {
        Query query1 = Query.query(Criteria.where("userId").is(userId).and("friendId").is(friendId));
        mongoTemplate.remove(query1, Friend.class);
        Query query2 = Query.query(Criteria.where("userId").is(friendId).and("friendId").is(userId));
        mongoTemplate.remove(query2, Friend.class);

    }


}
